package com.atom.module.mvvm.base

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding

abstract class AbstractActivity<V : ViewDataBinding, VM : IViewModel> : AppCompatActivity(),
    IView<VM> {

    protected lateinit var binding: V

    protected lateinit var viewModel: VM

    protected open fun initWindow() {}

    protected open fun initArgs(savedInstanceState: Bundle?): Boolean = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initWindow()
        if (initArgs(intent.extras)) {
            initData(initMVVM(savedInstanceState))
        } else {
            finish()
        }
    }

    abstract fun initContentView(savedInstanceState: Bundle?): Int

    abstract fun initVariableId(): Int

    protected open fun initViewBinding(binding: V, viewModel: VM) {}

    protected open fun initData(view: View) {}

    private fun initMVVM(savedInstanceState: Bundle?): View {
        this.binding = DataBindingUtil.setContentView(this, initContentView(savedInstanceState))
        this.binding.lifecycleOwner = this
        this.viewModel = initViewModel().also {
            it.lifecycleOwner(this)
            this.binding.setVariable(initVariableId(), it)
        }
        initViewBinding(this.binding, this.viewModel)
        return this.binding.root
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.unbind()
    }
}